package com.sadam.ui4.FragmentMessagePage;

import android.content.Context;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.PopupMenu;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.sadam.ui4.Data.Video;
import com.sadam.ui4.MainActivity;
import com.sadam.ui4.R;
import com.sadam.ui4.Data.User;
import com.sadam.ui4.Data.MySqLiteOpenHelper;
import com.sadam.ui4.Data.Comment;
import com.sadam.ui4.FragmentSelfPage.FragmentPersonalVideoPlayer;

import java.util.ArrayList;
import java.util.List;

/**
 * 消息页面 Fragment，用于展示用户收到的点赞和评论消息。
 * 支持通过顶部标签切换显示"点赞"或"评论"列表，并提供视觉反馈。
 */
public class FragmentMessagesPage extends Fragment {

    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    private String mParam1;
    private String mParam2;
    private OnFragmentInteractionListener mListener;

    private TextView tvLikeLabel;
    private TextView tvCommentLabel;
    private RecyclerView recyclerViewLikes;
    private RecyclerView recyclerViewComments;

    private LikeMessageAdapter likeAdapter;
    private CommentMessageAdapter commentAdapter;

    private List<LikeMessage> likeMessages;
    private List<CommentMessage> commentMessages;

    // 数据库和用户信息
    private MySqLiteOpenHelper dbHelper;
    private User currentUser;
    private SwipeRefreshLayout swipeRefreshLayout;

    public FragmentMessagesPage() {
        // Required empty public constructor
    }

    public static FragmentMessagesPage newInstance(String param1, String param2) {
        FragmentMessagesPage fragment = new FragmentMessagesPage();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater,
                             @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_messages_page, container, false);

        // 初始化下拉刷新
        swipeRefreshLayout = view.findViewById(R.id.swipe_refresh_layout);
        if (swipeRefreshLayout != null) {
            setupPullToRefresh();
        }

        // 获取数据库实例
        if (getActivity() instanceof MainActivity) {
            MainActivity mainActivity = (MainActivity) getActivity();
            dbHelper = mainActivity.getMySqLiteOpenHelper();
        } else {
            Toast.makeText(requireContext(), "无法获取数据库", Toast.LENGTH_SHORT).show();
            requireActivity().finish();
            return view;
        }

        // 获取当前用户
        currentUser = User.getCurrentUser(requireContext(), dbHelper);
        if (currentUser == null) {
            Toast.makeText(requireContext(), "请先登录", Toast.LENGTH_SHORT).show();
            requireActivity().finish();
            return view;
        }

        // 绑定 UI 控件
        tvLikeLabel = view.findViewById(R.id.tv_like_label);
        tvCommentLabel = view.findViewById(R.id.tv_comment_label);
        recyclerViewLikes = view.findViewById(R.id.likeRecyclerView);
        recyclerViewComments = view.findViewById(R.id.commentRecyclerView);

        // 设置 RecyclerView 布局管理器
        recyclerViewLikes.setLayoutManager(new LinearLayoutManager(requireContext()));
        recyclerViewComments.setLayoutManager(new LinearLayoutManager(requireContext()));

        // 初始化数据
        likeMessages = new ArrayList<>();
        commentMessages = new ArrayList<>();

        // 设置适配器
        likeAdapter = new LikeMessageAdapter(likeMessages);
        commentAdapter = new CommentMessageAdapter(commentMessages);
        recyclerViewLikes.setAdapter(likeAdapter);
        recyclerViewComments.setAdapter(commentAdapter);

        // 从数据库加载数据
        loadLikeMessagesFromDatabase();
        loadCommentMessagesFromDatabase();

        // 默认显示点赞列表
        showLikes();

        // 设置顶部标签点击事件
        view.findViewById(R.id.likeContainer).setOnClickListener(v -> showLikes());
        view.findViewById(R.id.commentContainer).setOnClickListener(v -> showComments());

        // 设置适配器点击监听
        setupAdaptersClickListener();

        return view;
    }

    /**
     * 深度刷新所有数据（包括评论数）
     * 供MainActivity调用，确保评论后数据完全同步
     */
    public void refreshAllData() {
        Log.d("FragmentMessagesPage", "🔄 开始深度刷新所有数据");

        // 重新加载消息数据
        refreshMessages();

        // 强制刷新适配器，确保UI更新
        if (likeAdapter != null) {
            likeAdapter.notifyDataSetChanged();
            Log.d("FragmentMessagesPage", "✅ 点赞适配器已刷新");
        }
        if (commentAdapter != null) {
            commentAdapter.notifyDataSetChanged();
            Log.d("FragmentMessagesPage", "✅ 评论适配器已刷新");
        }

        // 更新空状态提示
        updateEmptyState();

        Log.d("FragmentMessagesPage", "🎉 深度刷新完成");
    }

    /**
     * 刷新消息列表（增强版）
     */
    public void refreshMessages() {
        Log.d("FragmentMessagesPage", "🔄 刷新消息列表");

        if (swipeRefreshLayout != null) {
            swipeRefreshLayout.setRefreshing(true);
        }

        // 重新加载数据库数据
        loadLikeMessagesFromDatabase();
        loadCommentMessagesFromDatabase();

        Log.d("FragmentMessagesPage", "📥 消息数据重新加载中...");
    }

    private void setupPullToRefresh() {
        if (swipeRefreshLayout != null) {
            // 设置下拉刷新颜色
            swipeRefreshLayout.setColorSchemeColors(
                    Color.WHITE,
                    Color.parseColor("#FF4081"),
                    Color.parseColor("#3F51B5")
            );

            // 设置背景颜色
            swipeRefreshLayout.setProgressBackgroundColorSchemeColor(Color.parseColor("#1E1E1E"));

            swipeRefreshLayout.setOnRefreshListener(() -> {
                refreshMessages();
            });
        }
    }

    /**
     * 设置适配器点击监听
     */
    private void setupAdaptersClickListener() {
        // 评论消息点击监听
        commentAdapter.setOnMessageClickListener(video -> {
            openVideoPlayer(video);
        });

        // 点赞消息点击监听
        likeAdapter.setOnMessageClickListener(video -> {
            openVideoPlayer(video);
        });
    }

    /**
     * 打开视频播放器 - 复用现有的播放器，禁用滑动
     */
    private void openVideoPlayer(Video video) {
        if (video == null) {
            Toast.makeText(requireContext(), "视频数据异常", Toast.LENGTH_SHORT).show();
            return;
        }

        // 创建包含该视频的列表
        List<Video> videoList = new ArrayList<>();
        videoList.add(video);

        // 复用 FragmentPersonalVideoPlayer，但禁用滑动
        // 第三个参数 false 表示禁用滑动
        FragmentPersonalVideoPlayer player = FragmentPersonalVideoPlayer.newInstance(videoList, 0, false);
        player.show(getActivity().getSupportFragmentManager(), "message_video_player");

        Log.d("FragmentMessagesPage", "打开视频播放器，视频: " + video.getTitle() + "，禁用滑动");
    }

    /**
     * 从数据库加载点赞消息
     */
    private void loadLikeMessagesFromDatabase() {
        new AsyncTask<Void, Void, List<LikeMessage>>() {
            @Override
            protected List<LikeMessage> doInBackground(Void... voids) {
                List<LikeMessage> messages = new ArrayList<>();

                if (dbHelper == null || currentUser == null) {
                    Log.e("FragmentMessagesPage", "dbHelper 或 currentUser 为 null");
                    return messages;
                }

                try {
                    // 1. 获取当前用户发布的所有视频
                    ArrayList<Video> userVideos = dbHelper.getAllVideosByUser(currentUser);
                    if (userVideos.isEmpty()) {
                        Log.d("FragmentMessagesPage", "当前用户没有发布视频");
                        return messages;
                    }

                    // 2. 查询点赞记录 - 使用数据库实例的方法
                    for (Video video : userVideos) {
                        // 获取这个视频的点赞用户列表
                        List<User> likers = getLikersForVideo(video.getId());
                        for (User liker : likers) {
                            // 获取点赞时间
                            long likeTime = getLikeTime(video.getId(), liker.getId());
                            LikeMessage message = new LikeMessage(
                                    liker.getName(),
                                    liker.getAvatarPath(),
                                    video.getTitle(),
                                    video.getVideoFilePath(),
                                    likeTime,
                                    video  // 直接传入Video对象
                            );
                            messages.add(message);
                        }
                    }

                    // 按时间倒序排序
                    messages.sort((m1, m2) -> Long.compare(m2.getLikeTime(), m1.getLikeTime()));

                } catch (Exception e) {
                    Log.e("FragmentMessagesPage", "加载点赞消息失败", e);
                }

                return messages;
            }

            @Override
            protected void onPostExecute(List<LikeMessage> messages) {
                likeMessages.clear();
                likeMessages.addAll(messages);
                likeAdapter.notifyDataSetChanged();
                Log.d("FragmentMessagesPage", "从数据库加载了 " + messages.size() + " 条点赞消息");

                // 停止刷新动画
                if (swipeRefreshLayout != null && swipeRefreshLayout.isRefreshing()) {
                    swipeRefreshLayout.setRefreshing(false);
                }

                // 更新界面提示
                updateEmptyState();
            }
        }.execute();
    }

    /**
     * 获取视频的点赞用户列表
     */
    private List<User> getLikersForVideo(long videoId) {
        List<User> likers = new ArrayList<>();
        String sql = "SELECT u.* FROM User u " +
                "JOIN LikeTable l ON u.id = l.user_id " +
                "WHERE l.video_id = ? AND u.isDeleted = 0";

        Cursor cursor = dbHelper.getReadableDatabase().rawQuery(sql, new String[]{String.valueOf(videoId)});

        if (cursor != null && cursor.moveToFirst()) {
            try {
                // 获取列索引（一次性获取，提高效率）
                int idIndex = cursor.getColumnIndex("id");
                int nameIndex = cursor.getColumnIndex("name");
                int passwordIndex = cursor.getColumnIndex("password");
                int avatarPathIndex = cursor.getColumnIndex("avatarPath");
                int introIndex = cursor.getColumnIndex("selfIntroduction");

                // 检查关键列是否存在
                if (idIndex == -1 || nameIndex == -1 || passwordIndex == -1) {
                    Log.e("FragmentMessagesPage", "数据库查询结果缺少必要列：id, name 或 password");
                    return likers;
                }

                do {
                    long userId = cursor.getLong(idIndex);
                    String username = cursor.getString(nameIndex);
                    String password = cursor.getString(passwordIndex);
                    String avatarPath = avatarPathIndex == -1 ? null : cursor.getString(avatarPathIndex);
                    String selfIntroduction = introIndex == -1 ? null : cursor.getString(introIndex);

                    User user = new User(dbHelper, userId, username, password);
                    user.setAvatarPath(avatarPath);
                    user.setSelfIntroduction(selfIntroduction);
                    likers.add(user);
                } while (cursor.moveToNext());
            } catch (Exception e) {
                Log.e("FragmentMessagesPage", "解析用户数据时出错", e);
            } finally {
                cursor.close();
            }
        }

        return likers;
    }

    /**
     * 获取点赞时间
     */
    private long getLikeTime(long videoId, long userId) {
        String sql = "SELECT like_time FROM LikeTable WHERE video_id = ? AND user_id = ?";
        Cursor cursor = dbHelper.getReadableDatabase().rawQuery(sql, new String[]{
                String.valueOf(videoId), String.valueOf(userId)
        });

        long likeTime = System.currentTimeMillis();
        if (cursor != null && cursor.moveToFirst()) {
            int timeIndex = cursor.getColumnIndex("like_time");
            if (timeIndex != -1) {
                likeTime = cursor.getLong(timeIndex);
            } else {
                Log.w("FragmentMessagesPage", "无法找到列：like_time");
            }
            cursor.close();
        }

        return likeTime;
    }

    /**
     * 从数据库加载评论消息
     */
    private void loadCommentMessagesFromDatabase() {
        new AsyncTask<Void, Void, List<CommentMessage>>() {
            @Override
            protected List<CommentMessage> doInBackground(Void... voids) {
                List<CommentMessage> messages = new ArrayList<>();

                if (dbHelper == null || currentUser == null) {
                    Log.e("FragmentMessagesPage", "dbHelper 或 currentUser 为 null");
                    return messages;
                }

                try {
                    // 1. 获取当前用户发布的所有视频
                    ArrayList<Video> userVideos = dbHelper.getAllVideosByUser(currentUser);
                    if (userVideos.isEmpty()) {
                        Log.d("FragmentMessagesPage", "当前用户没有发布视频");
                        return messages;
                    }

                    // 2. 遍历每个视频，查询其评论
                    for (Video video : userVideos) {
                        List<Comment> comments = dbHelper.getCommentsByVideoId(video.getId());
                        for (Comment comment : comments) {
                            // ✅ 修正：传递 Video 对象而不是字符串
                            CommentMessage message = new CommentMessage(
                                    comment.getUserName(),
                                    comment.getContent(),
                                    comment.getTime(),
                                    comment.getUserAvatarUrl(),
                                    video.getTitle(),
                                    video  // ✅ 这里传递 Video 对象
                            );
                            messages.add(message);
                        }
                    }

                    // ✅ 按时间戳倒序排序（最新在前）
                    messages.sort((m1, m2) -> Long.compare(m2.getTimestamp(), m1.getTimestamp()));

                } catch (Exception e) {
                    Log.e("FragmentMessagesPage", "加载评论消息失败", e);
                }

                return messages;
            }

            @Override
            protected void onPostExecute(List<CommentMessage> messages) {
                commentMessages.clear();
                commentMessages.addAll(messages);
                commentAdapter.notifyDataSetChanged();
                Log.d("FragmentMessagesPage", "从数据库加载了 " + messages.size() + " 条评论消息");

                // 停止刷新动画
                if (swipeRefreshLayout != null && swipeRefreshLayout.isRefreshing()) {
                    swipeRefreshLayout.setRefreshing(false);
                }

                updateEmptyState();
            }
        }.execute();
    }

    /**
     * 计算时间差
     */
    private String calculateTimeAgo(long timestamp) {
        long now = System.currentTimeMillis();
        long diff = now - timestamp;

        long seconds = diff / 1000;
        long minutes = seconds / 60;
        long hours = minutes / 60;
        long days = hours / 24;

        if (minutes < 1) {
            return "刚刚";
        } else if (minutes < 60) {
            return minutes + "分钟前";
        } else if (hours < 24) {
            return hours + "小时前";
        } else if (days < 7) {
            return days + "天前";
        } else {
            java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("M月d日", java.util.Locale.CHINA);
            return sdf.format(new java.util.Date(timestamp));
        }
    }

    /**
     * 更新空状态提示
     */
    private void updateEmptyState() {
        if (likeMessages.isEmpty() && commentMessages.isEmpty()) {
            Toast.makeText(requireContext(), "暂无消息", Toast.LENGTH_SHORT).show();
        } else if (likeMessages.isEmpty() && recyclerViewLikes.getVisibility() == View.VISIBLE) {
            Log.d("updateEmptyState","正常显示作品栏");
        } else if (commentMessages.isEmpty() && recyclerViewComments.getVisibility() == View.VISIBLE) {
            Toast.makeText(requireContext(), "暂无评论消息", Toast.LENGTH_SHORT).show();
        }
    }

    // 显示点赞/评论
    private void showLikes() {
        tvLikeLabel.setTextColor(Color.WHITE);
        tvCommentLabel.setTextColor(Color.parseColor("#B3FFFFFF"));
        recyclerViewLikes.setVisibility(View.VISIBLE);
        recyclerViewComments.setVisibility(View.GONE);

        if (likeMessages.isEmpty()) {
            Toast.makeText(requireContext(), "暂无点赞消息", Toast.LENGTH_SHORT).show();
        }
    }

    private void showComments() {
        tvCommentLabel.setTextColor(Color.WHITE);
        tvLikeLabel.setTextColor(Color.parseColor("#B3FFFFFF"));
        recyclerViewComments.setVisibility(View.VISIBLE);
        recyclerViewLikes.setVisibility(View.GONE);

        if (commentMessages.isEmpty()) {
            Toast.makeText(requireContext(), "暂无评论消息", Toast.LENGTH_SHORT).show();
        }
    }

    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    public interface OnFragmentInteractionListener {
        void onFragmentInteraction(Uri uri);
    }
}